package hotel.meituan.oversea.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.constant.MeituanConstants;
import hotel.base.oversea.constant.enums.CommonEnums;
import hotel.base.oversea.constant.enums.MessageEnums;
import hotel.base.oversea.constant.enums.MtHotelEnums;
import hotel.base.oversea.service.impl.BaseServiceImpl;
import hotel.base.oversea.utils.*;
import hotel.base.oversea.vo.meituan.MtHotelOrderJobDealVo;
import hotel.base.oversea.vo.meituan.request.order.MtHotelOrderCheckParamVo;
import hotel.base.oversea.vo.meituan.response.order.MtHotelOrderCheckPricesVo;
import hotel.base.oversea.vo.meituan.response.order.MtHotelOrderCheckVo;
import hotel.meituan.oversea.api.entity.MtHotelOrderBooking;
import hotel.meituan.oversea.api.entity.MtHotelOrderStateHistory;
import hotel.meituan.oversea.api.vo.down.request.order.MtHotelOrderBookingParamVo;
import hotel.meituan.oversea.api.vo.down.request.order.MtHotelOrderCancelParamVo;
import hotel.meituan.oversea.api.vo.switchs.OperateDltOrderVo;
import hotel.meituan.oversea.api.vo.up.response.order.MtHotelOrderBookingVo;
import hotel.meituan.oversea.api.vo.up.response.order.MtHotelOrderCancelVo;
import hotel.meituan.oversea.biz.config.service.RedisService;
import hotel.meituan.oversea.biz.mapper.MtHotelOrderBookingMapper;
import hotel.meituan.oversea.biz.service.MtHotelOrderDealService;
import hotel.meituan.oversea.biz.service.MtHotelOrderDealSplitService;
import hotel.meituan.oversea.biz.service.MtHotelOrderService;
import hotel.meituan.oversea.biz.task.MeituanSplitMasterOrderCancelTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;
import tk.mybatis.mapper.entity.Example;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class MtHotelOrderDealSplitServiceImpl extends BaseServiceImpl implements MtHotelOrderDealSplitService {
    @Autowired
    private MtHotelOrderBookingMapper mtHotelOrderBookingMapper;

    @Autowired
    private MtHotelOrderService mtHotelOrderService;
    @Autowired
    private MtHotelOrderDealService mtHotelOrderDealService;
    @Autowired
    private MeituanSplitMasterOrderCancelTask meituanSplitMasterOrderCancelTask;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisService redisService;

    /**
     * 【拆弹采购】
     * 拆单后判断多笔拆单都可采购，才可以则直接采购；一般来说多笔下单前校验都通过则采购成功率很高，若出现一笔失败的情况，则程序做判断主动申请子单取消  出现预订失败的情况 1、同时失败：直接操作其他所有已预订成功子单取消  2、异步通知的失败：异步做判断，直接操作其他所有已预订成功子单取消
     * @param mtHotelOrderJobDealVo
     * @param mtHotelOrderCheckVoFirst
     * @param checkPriceResult
     * @param swOrderId
     * @param mtHotelId
     * @param goodsId
     * @param swPoolId
     * @param checkinDate
     * @param checkoutDate
     * @return
     */
    //
    @Override
    public Result bookingPaySplitOrder(Boolean hhbOperTodo, MtHotelOrderJobDealVo mtHotelOrderJobDealVo,MtHotelOrderCheckVo mtHotelOrderCheckVoFirst,
                                       String checkPriceResult,String swOrderId,String mtHotelId,Integer goodsId,String swPoolId,String checkinDate, String checkoutDate) {
        log.info("bookingPaySplitOrder 当前进入预先拆单mtHotelOrderJobDealVo={}",GsonUtils.GsonString(mtHotelOrderJobDealVo));
        Result mtDisOrderIdIndexResult = mtHotelOrderDealService.getMtDisOrderIdIndex(swOrderId,mtHotelId,goodsId,swPoolId);
        if(mtDisOrderIdIndexResult.getCode()==CommonConstants.SUCCESS){
            String master_mtDisOrderId_index  = (String)mtDisOrderIdIndexResult.getData();
            Integer frontSwTotalPrice = mtHotelOrderJobDealVo.getTotalPrice();//下游携程订单总价
            Integer masterRoomnum = mtHotelOrderJobDealVo.getRoomnum();

            //生成主订单
            MtHotelOrderBookingParamVo masterMtHotelOrderBookingParamVo = buildThisDaysOrderAMasterOrder(master_mtDisOrderId_index,swOrderId,mtHotelId,goodsId,checkPriceResult,
                    mtHotelOrderCheckVoFirst,masterRoomnum,mtHotelOrderJobDealVo,checkinDate,checkoutDate);//当前没有设置订单价格和settlePrice

            //更新pool相关美团id --》为了取消订单正常
            mtHotelOrderDealService.updateOrderPoolBookingSuccess(null, mtHotelOrderJobDealVo,masterMtHotelOrderBookingParamVo.getDistributorOrderId(),masterMtHotelOrderBookingParamVo.getDistributorOrderId());

            Long days = DateUtil.dateDiff(checkinDate,"day",checkoutDate,"yyyy-MM-dd");
            List<MtHotelOrderBooking> childOrderList = new ArrayList<>();

            //先生成多笔子订单美团库表数据
            buildManyOneDayChildOrder(frontSwTotalPrice,master_mtDisOrderId_index,days,swOrderId,masterMtHotelOrderBookingParamVo,childOrderList);

            //每一笔子订单独立进行下单前校验
            Map<String,MtHotelOrderCheckVo> childCheckVoMap = new HashMap<>();
            Result onedaycheckResult = oneDayOrderToOrderCheck(frontSwTotalPrice,days,checkinDate,checkoutDate,childOrderList,mtHotelId,goodsId,masterRoomnum,childCheckVoMap);

            //全部子订单下单前校验通过后，可进行后续操作
            ///Boolean hhbOperTodo = false;//很好办人工操作拆单直采，不考虑亏损超出上限
            Map<String,Map<String,String>> childPriceMap = new HashMap<>();
            if(onedaycheckResult.getCode()==CommonConstants.SUCCESS){
                //校验通过，对订单设置订单金额
                String endCheckJson = (String)onedaycheckResult.getData();
                MtHotelOrderCheckVo endCheckVo = GsonUtils.GsonToBean(endCheckJson,MtHotelOrderCheckVo.class);
                if(null != endCheckVo && endCheckVo.getPriceModels().size()>0){
                    List<MtHotelOrderCheckPricesVo> thisOrderPriceList = endCheckVo.getPriceModels();
                    BigDecimal masterSaleTotalPrice = new BigDecimal(0);
                    BigDecimal masterSettleTotalPrice = new BigDecimal(0);
                    for (MtHotelOrderCheckPricesVo v:thisOrderPriceList){
                        String date = v.getDate();
                        BigDecimal sale = BigDecimal.valueOf(v.getSalePrice());
                        BigDecimal sub = BigDecimal.valueOf(v.getSubPrice());
                        BigDecimal settle = sale.subtract(sub);
                        Map<String,String> thisPriceDateChildMap = new HashMap<>();
                        thisPriceDateChildMap.put(sale.toString(),settle.toString());
                        childPriceMap.put(date,thisPriceDateChildMap);
                        BigDecimal saleTotalPrice = sale.multiply(BigDecimal.valueOf(masterRoomnum));//订单市场总价
                        BigDecimal settleTotalPrice = settle.multiply(BigDecimal.valueOf(masterRoomnum));//订单结算价总价
                        masterSaleTotalPrice = masterSaleTotalPrice.add(saleTotalPrice);
                        masterSettleTotalPrice = masterSettleTotalPrice.add(settleTotalPrice);
                    }
                    if(childOrderList.size()==childPriceMap.size()){
                        //主单订单价格
                        mtHotelOrderService.updatePriceByOrderIndexId(masterMtHotelOrderBookingParamVo.getDistributorOrderId(),masterSaleTotalPrice.intValue(),masterSettleTotalPrice.intValue());
                        for (MtHotelOrderBooking c:childOrderList){
                            String thisCheckin = c.getMtCheckinDate();
                            if(null != childPriceMap.get(thisCheckin)){
                                Map<String,String> thiscp = childPriceMap.get(thisCheckin);
                                Integer childTotalP = 0 ;
                                Integer childSettleP = 0 ;
                                for (Map.Entry e:thiscp.entrySet()){
                                    childTotalP = Integer.valueOf((String)e.getKey());
                                    childSettleP = Integer.valueOf((String)e.getValue());
                                }
                                //子单订单价格
                                //子单订单价格
                                childTotalP = BigDecimal.valueOf(childTotalP).multiply(BigDecimal.valueOf(masterRoomnum)).intValue();
                                childSettleP = BigDecimal.valueOf(childSettleP).multiply(BigDecimal.valueOf(masterRoomnum)).intValue();
                                mtHotelOrderService.updatePriceByOrderIndexId(c.getMtDistributorOrderId(),childTotalP,childSettleP);
                            }else{
                                onedaycheckResult.setMsg(onedaycheckResult.getMsg()+"--》程序内部判断下单前校验日历价格childPriceMap不匹配");
                                onedaycheckResult.setCode(CommonConstants.REQUEST_ERROR);
                                break;
                            }
                        }
                    }else{
                        onedaycheckResult.setMsg(onedaycheckResult.getMsg()+"--》程序内部判断下单前校验日历价格数据异常");
                        onedaycheckResult.setCode(CommonConstants.REQUEST_ERROR);
                    }

                }else{
                    onedaycheckResult.setMsg(onedaycheckResult.getMsg()+"--》程序内部重新赋值订单金额异常");
                    onedaycheckResult.setCode(CommonConstants.REQUEST_ERROR);
                }
            }

            if(onedaycheckResult.getCode()==CommonConstants.SUCCESS){
                //校验通过

            }else{
                if(hhbOperTodo){
                    //SendUtils.dingMsgNotLog("[SPLIT-RG-HHB] 后台人工操作拆单直采，不考虑拆单采购后总价亏损超过上限 ",DateUtil.getCurrTime()+" 连住主订单号："+swOrderId+" 入住离店时间："+checkinDate+"+"+checkoutDate+" 房间数："+masterRoomnum,MessageEnums.genre.DELAYED_ORDER.getCode(),restTemplate);
                }else{
                    //校验不通过不可拆单拆单失败：将主单和子单state设置为等于1 ，失效订单（没有下过单的子单可直接改为state=1失效，下过单的子单不可）
                    mtHotelOrderService.updateSplitOrderIsFailed(master_mtDisOrderId_index);

                    SendUtils.dingMsgNotLog("[SPLIT-ERROR] 拆单分析，拆后所有子单校验分析不通过 o(╥﹏╥)o 。。。。。。。。。。 ",DateUtil.getCurrTime()+" 失败原因："+GsonUtils.GsonString(onedaycheckResult)
                            +" 连住主订单号："+swOrderId+" 入住离店时间："+checkinDate+"+"+checkoutDate+" 房间数："+masterRoomnum,MessageEnums.genre.DELAYED_ORDER.getCode(),restTemplate);
                    return new Result(onedaycheckResult.toString(),CommonConstants.REQUEST_ERROR);//返回给携程预下单失败
                }
            }

            ////////////////////////////////////////////////////  拆单采购  /////////////////////////////////////////////

            SendUtils.dingMsgNotLog("[SPLIT-TODO] 拆单分析，"+days+" 笔子单通过校验，程序采购中 ^ 0 ^ 。。。。。。。。。。 ",DateUtil.getCurrTime()+
                    " 连住主订单号："+swOrderId+" 入住离店时间："+checkinDate+"+"+checkoutDate+" 房间数："+masterRoomnum,MessageEnums.genre.ORDER_NOTICY.getCode(),restTemplate);

            String checkResMsg = (String)onedaycheckResult.getMsg();
            Boolean isLoss = false;//是否允许范围内的亏损单
            String isLossMsg = "";
            if(!ObjectUtils.isEmpty(checkResMsg) && checkResMsg.contains("isLoss_")){
                isLoss = true;
                isLossMsg = checkResMsg.split("_")[2];
            }

            //校验价格通过，程序可进行统一采购;若预下单出现一单不成功，则回滚取消
            boolean thisBookingSuccessNeedToCancel = false;
            Result oneDayOrderBookingResultError = null;
            for (int i = 0; i <childOrderList.size() ; i++) {

                if(null != redisService.get("split_booking_submit_stop"+master_mtDisOrderId_index)){
                    log.info("split_booking_submit_stop 1、用户申请取消主单   2、异步通知预订失败   ---------》》 当前for预订子单将被中断");
                    break;//  1、用户申请取消主单   2、异步通知预订失败   ---------》》 当前for预订子单将被中断
                }

                MtHotelOrderBooking childBooking = childOrderList.get(i);
                String childOrderIndexId = childBooking.getMtDistributorOrderId();
                //子单预下单
                //构建一个主单信息的MtHotelOrderCheckParamVo
                MtHotelOrderCheckVo mtHotelOrderCheckVoNew = new MtHotelOrderCheckVo();
                mtHotelOrderCheckVoNew = childCheckVoMap.get(childBooking.getMtCheckinDate());

                Result oneDayOrderBookingResult = this.bookingSplit(mtHotelOrderCheckVoNew,childOrderIndexId,master_mtDisOrderId_index,mtHotelId,goodsId,childBooking.getMtCheckinDate(),childBooking.getMtCheckoutDate(),childBooking.getMtRoomNum(),childBooking.getMtPersonNames(),childBooking.getMtContactName());
                Object thisChildOrderMtRetuanBookingVo = oneDayOrderBookingResult.getData();
                MtHotelOrderBookingVo thisChildOrderBooking = JacksonUtil.objToBean(thisChildOrderMtRetuanBookingVo, MtHotelOrderBookingVo.class);
                if (oneDayOrderBookingResult.getCode() == CommonConstants.SUCCESS && null != thisChildOrderBooking) {
                    if(thisChildOrderBooking.getCode() !=0){//不等于0失败
                        thisBookingSuccessNeedToCancel =true;
                        SendUtils.dingMsgNotLog("[WAITING-SPLIT] 第 "+i+" 笔子单预下单已提交 ",DateUtil.getCurrTime()+" 子订单号："+childOrderIndexId+" 主订单号："+master_mtDisOrderId_index,MessageEnums.genre.ORDER_NOTICY.getCode(),restTemplate);
                    }else{
                        //修改子单状态为 预下单已提交状态
                        mtHotelOrderService.updateOneChildOrderStatus(master_mtDisOrderId_index,childOrderIndexId,MtHotelEnums.orderStateEnum.BOOKING.getCode(),thisChildOrderBooking.getMtOrderId());
                    }
                }else{//失败
                    thisBookingSuccessNeedToCancel =true;
                }
                oneDayOrderBookingResultError = oneDayOrderBookingResult;

                if(thisBookingSuccessNeedToCancel){

                    log.info("出现一单预下单不成功则停止采购，并且以往采购了的进行取消操作：size={},,i={},,master_mtDisOrderId_index={},failedchildBooking={}",
                            childOrderList.size(),i,master_mtDisOrderId_index,GsonUtils.GsonString(childBooking));
                    break;
                }
            }
            if(thisBookingSuccessNeedToCancel){

                SendUtils.dingMsgNotLog("[SPLIT-BOOKING-ERROR] 有一子单预下单失败了，程序停止拆单采购 o(╥﹏╥)o 。。。。。。。。。。 ",DateUtil.getCurrTime()+" 子单失败原因："+GsonUtils.GsonString(oneDayOrderBookingResultError)
                        +" 连住主订单号："+swOrderId+" 房间数："+masterRoomnum,MessageEnums.genre.DELAYED_ORDER.getCode(),restTemplate);
                //出现一单 "预下单" 不成功则停止采购，并且以往采购了的进行取消操作；
                Result cancelRes = cancelOtherChildSplitOrder(master_mtDisOrderId_index,GsonUtils.GsonString(oneDayOrderBookingResultError),"splitBookingCancel");
                String cancelError = "";
                if(cancelRes.getCode()!=CommonConstants.SUCCESS){
                    cancelError = GsonUtils.GsonString(cancelRes);
                }
                //出现某一单预下单失败了，将主单改为失效，子单可不改(异步通知同理) --> 上面有涉及获取主单（id+state）-->所以失效放在后面
                mtHotelOrderService.updateOneMasterSplitOrderIsFailed(master_mtDisOrderId_index,null,null);
                return new Result("有一子单预下单失败停止拆单采购 失败返回:"+oneDayOrderBookingResultError.toString()+" 取消："+cancelError,CommonConstants.REQUEST_ERROR);//返回给携程预下单失败
            }else{
                if(isLoss){
                    try{
                        SendUtils.dingMsgNotLog("新连住拆单 发生允许范围内亏损 ",DateUtil.getCurrTime()+" 订单号："+swOrderId+" 携程订单价格："+isLossMsg.split("_")[1]+" 美团所有子单总采购结算价："+isLossMsg.split("_")[2],MessageEnums.genre.ORDER_LOSS.getCode(),restTemplate);
                    }catch (Exception e){
                        log.error("新连住订单亏损单发送钉钉异常:"+e.getMessage());
                        e.printStackTrace();
                    }
                }
                //等待异步通知--》在异步通知那边判断为最后一笔子单完成预定，推送该钉钉消息
                    /*SendUtils.dingMsgNotLog("[SPLIT-SUCCESS] 所有子单成功采购完成 ^ 0 ^ ^ 0 ^  ",DateUtil.getCurrTime()+
                            " 连住主订单号："+swOrderId+" 入住离店时间："+checkinDate+"+"+checkoutDate+" 房间数："+masterRoomnum,MessageEnums.genre.ORDER_NOTICY.getCode(),restTemplate);*/
            }
            /////////////////////////////////////////////////  拆单采购  ///////////////////////////////////////////

            return new Result();
        }else{
            log.error("bookingPaySplitOrder 获取主订单订单号失败："+GsonUtils.GsonString(mtDisOrderIdIndexResult));
            return mtDisOrderIdIndexResult;
        }
    }

    /**
     * 生成子订单 (主单没有设置价格和settleprice 等校验通过后再设置)
     * @param days
     * @param swOrderId
     * @param mtHotelOrderBookingParamVo1
     * @param childOrderList
     */
    private void buildManyOneDayChildOrder(Integer frontSwTotalPrice, String master_mtDisOrderId_index, Long days, String swOrderId, MtHotelOrderBookingParamVo mtHotelOrderBookingParamVo1, List<MtHotelOrderBooking> childOrderList) {
        MtHotelOrderBookingParamVo newMtPVo = new MtHotelOrderBookingParamVo();
        BeanCopierUtil.copy(mtHotelOrderBookingParamVo1,newMtPVo);
        log.info("生成子订单数据："+days+"笔拆单");
        String thirdChar = returnOrderThirdChar(master_mtDisOrderId_index);
        String mtDate = newMtPVo.getCheckinDate();
        for (int i = 1; i <= days; i++) {
            String nextDay = DateUtil.formatDate(DateUtil.addDay(mtDate,1),"yyyy-MM-dd");
            String thisIndex = String.valueOf(i);
            if(i<10){
                thisIndex = "0"+i;
            }
            String newChildOrderIndexOrderId = master_mtDisOrderId_index+thirdChar+thisIndex;//子单命名：维持后三位的改动，因为其他地方涉及截取掉后三位，获得swOrderId
            log.info(master_mtDisOrderId_index+" 第 "+i+" 笔拆单："+newChildOrderIndexOrderId);
            newMtPVo.setDistributorOrderId(newChildOrderIndexOrderId);
            MtHotelOrderBookingVo mtHotelOrderBookingVoChild = new MtHotelOrderBookingVo();
            mtHotelOrderBookingVoChild.setDesc("价格校验失败,生成主订单和拆单数据，当前为子单保存订单信息："+newChildOrderIndexOrderId);

            MtHotelOrderBookingParamVo mtHotelOrderBookingParamVoNewNew = new MtHotelOrderBookingParamVo();
            BeanCopierUtil.copy(newMtPVo,mtHotelOrderBookingParamVoNewNew);
            mtHotelOrderBookingParamVoNewNew.setCheckinDate(mtDate);
            mtHotelOrderBookingParamVoNewNew.setCheckoutDate(nextDay);
            MtHotelOrderBooking thisNewChildOrder = mtHotelOrderService.saveRequsetOrderBooking(mtHotelOrderBookingVoChild,mtHotelOrderBookingParamVoNewNew,MtHotelEnums.orderStateEnum.CREATE.getCode(), CommonEnums.STATE_NORMAL.getCode()
                    ,newChildOrderIndexOrderId,null,master_mtDisOrderId_index,2,null);//子单不保存swOrderId，其他地方涉及根据swOrderId获取美团订单
            childOrderList.add(thisNewChildOrder);
            mtDate = nextDay;
        }
    }

    /**
     * 子订单 订单号规则  倒数第三位用字母
     * @param master_mtDisOrderId_index
     * @return
     */
    private String returnOrderThirdChar(String master_mtDisOrderId_index) {
        String thirdChar = "C";
        try {
            String childChar = findOrderExsitChildGetChar(master_mtDisOrderId_index);
            if(!ObjectUtils.isEmpty(childChar)){
                thirdChar = new String(new byte[]{(byte) (childChar.getBytes("ASCII")[0]+1)},"ASCII");//获取顺位下一个字母
            }
        } catch (UnsupportedEncodingException e) {
            log.info("279子单订单号获取异常："+e.getMessage());
            e.printStackTrace();
            thirdChar = "Z";
        }
        return thirdChar;
    }

    /**
     * 为连住订单 生成 主订单
     * @param master_mtDisOrderId_index
     * @param swOrderId
     * @param mtHotelId
     * @param goodsId
     * @param checkPriceResult
     * @param mtHotelOrderCheckVo
     * @param masterRoomnum
     * @param mtHotelOrderJobDealVo
     * @param checkinDate
     * @param checkoutDate
     * @return
     */
    private MtHotelOrderBookingParamVo buildThisDaysOrderAMasterOrder(String master_mtDisOrderId_index, String swOrderId, String mtHotelId, Integer goodsId, String checkPriceResult,
                                                                      MtHotelOrderCheckVo mtHotelOrderCheckVo, Integer masterRoomnum, MtHotelOrderJobDealVo mtHotelOrderJobDealVo, String checkinDate, String checkoutDate) {
        log.info("进入生成主订单 buildThisDaysOrderAMasterOrder ：master_mtDisOrderId_index={}",master_mtDisOrderId_index);
        //响应数据保存订单变化日志
        MtHotelOrderStateHistory stateHistory = new MtHotelOrderStateHistory();
        stateHistory.setMtDistributorOrderId(master_mtDisOrderId_index);
        stateHistory.setSwOrderId(swOrderId);
        stateHistory.setMasterOrderId(master_mtDisOrderId_index);
        stateHistory.setMtHotelId(mtHotelId);
        stateHistory.setMtGoodsId(String.valueOf(goodsId));
        stateHistory.setMtOrderId(null);
        stateHistory.setMethod("下单前校验失败");
        stateHistory.setMethodName("下单前校验失败,当前为连住订单进行数据拆单");
        stateHistory.setStatusCode(null);
        stateHistory.setStatusDesc(null);
        stateHistory.setClassName("MtHotelOrderBookingVo");
        stateHistory.setClassJson(DateUtil.getCurrTime()+"：价格校验失败："+checkPriceResult);
        stateHistory.setRemark(null);
        //保存日志
        mtHotelOrderService.saveOrderStateHistory(stateHistory);

        log.info("生成主订单master_mtDisOrderId_index={}",master_mtDisOrderId_index);
        //美团下单前校验返回最新价格 priceModels
        /*List<MtHotelOrderCheckPricesVo> priceModels = mtHotelOrderCheckVo.getPriceModels();
        int mtShowSaleTotalPrice = 0;//美团订单市场价总价
        int subPrice = 0;//美团分销商佣金
        for (MtHotelOrderCheckPricesVo priceModel : priceModels) {
            //美团采购订单总价 * 房间数
            mtShowSaleTotalPrice = mtShowSaleTotalPrice + (priceModel.getSalePrice() * masterRoomnum);
            //每间佣金 * 房间数
            subPrice = subPrice + (priceModel.getSubPrice() * masterRoomnum);
        }*/
        //Integer costTotalPrice = BigDecimal.valueOf(mtShowSaleTotalPrice).subtract(BigDecimal.valueOf(subPrice)).intValue();//结算采购成本总价=总价减去分销商佣金

        MtHotelOrderBookingParamVo mtHotelOrderBookingParamVo = new MtHotelOrderBookingParamVo();
        mtHotelOrderBookingParamVo.setDistributorOrderId(master_mtDisOrderId_index);
        mtHotelOrderBookingParamVo.setHotelId(mtHotelId);
        mtHotelOrderBookingParamVo.setGoodsId(String.valueOf(goodsId));
        mtHotelOrderBookingParamVo.setPersonNames(mtHotelOrderJobDealVo.getPersonNames());
        mtHotelOrderBookingParamVo.setContactName(mtHotelOrderJobDealVo.getContactName());
        //todo 携程订单联系人电话暂无,使用400号码
        mtHotelOrderBookingParamVo.setContactPhone(StringUtil.getQueuePhone(redisTemplate));
        mtHotelOrderBookingParamVo.setMtHotelOrderCheckVo(mtHotelOrderCheckVo);
        mtHotelOrderBookingParamVo.setCheckinDate(checkinDate);
        mtHotelOrderBookingParamVo.setCheckoutDate(checkoutDate);
        mtHotelOrderBookingParamVo.setRoomNum(masterRoomnum);
        mtHotelOrderBookingParamVo.setTotalPrice(null);
        mtHotelOrderBookingParamVo.setSettlePrice(null);
        mtHotelOrderBookingParamVo.setMtHotelOrderCheckVo(mtHotelOrderCheckVo);

        MtHotelOrderBookingVo mtHotelOrderBookingVo = new MtHotelOrderBookingVo();
        mtHotelOrderBookingVo.setDesc("价格校验失败,生成主订单和拆单数据："+checkPriceResult);
        //该订单不设置STATE_ERROR，该订单状态为正常单且该订单仅可人工改为已完单，不可做其他操作如对该主单进行采购，只能对子单进行采购；；且pool表不设置为延时单应设置为42人工处理拆单状态单
        mtHotelOrderService.saveRequsetOrderBooking(mtHotelOrderBookingVo,mtHotelOrderBookingParamVo,MtHotelEnums.orderStateEnum.SPLIT_WAIT.getCode(), CommonEnums.STATE_NORMAL.getCode()
                ,master_mtDisOrderId_index,swOrderId,master_mtDisOrderId_index,1,mtHotelOrderJobDealVo.getTotalPrice());
        return mtHotelOrderBookingParamVo;
    }

    /**
     * 遍历每个子单，进行下单前校验（单日子单）
     * @param frontSwTotalPrice
     * @param days
     * @param checkinDate
     * @param childOrderList
     * @param mtHotelId
     * @param goodsId
     * @param masterRoomnum
     * @return
     */
    private Result oneDayOrderToOrderCheck(Integer frontSwTotalPrice, Long days, String checkinDate, String checkoutDate, List<MtHotelOrderBooking> childOrderList, String mtHotelId, Integer goodsId, Integer masterRoomnum, Map<String,MtHotelOrderCheckVo> childCheckVoMap) {
        log.info("遍历每个子单，进行下单前校验（单日子单）进入方法 oneDayOrderToOrderCheck ：childOrderList={}",GsonUtils.GsonString(childOrderList));
        //多笔单住子单，进行下单前校验是否可直接采购：多笔子单的总价 与 携程用户提供的订单总价 相比较
        String startDate = checkinDate;
        List<MtHotelOrderCheckPricesVo> priceModelsNew = new ArrayList<>();
        Map<String,String> childErrorMsgMap = new HashMap<>();
        BigDecimal allChildRealTotalPrice = new BigDecimal(0);//底价
        Integer remianRoomNum = 1;
        for (int i = 0; i < childOrderList.size(); i++) {
            String nextDay = DateUtil.formatDate(DateUtil.addDay(startDate,1),"yyyy-MM-dd");
            MtHotelOrderCheckParamVo mtHotelOrderCheckParamVo = new MtHotelOrderCheckParamVo();
            mtHotelOrderCheckParamVo.setHotelId(Long.valueOf(mtHotelId));
            mtHotelOrderCheckParamVo.setGoodsId(goodsId);
            mtHotelOrderCheckParamVo.setCheckinDate(startDate);
            mtHotelOrderCheckParamVo.setCheckoutDate(nextDay);
            mtHotelOrderCheckParamVo.setRoomNum(masterRoomnum);
            mtHotelOrderCheckParamVo.setTotalPrice(900000);//该价格设为很高，让子单不会因价格亏损不通过校验，因为价格我们先得到所有子单的价格后相加起来算的
            Result resultCheck = mtHotelOrderService.orderCheckApi(mtHotelOrderCheckParamVo);
//            if(i == 0){
//                resultCheck= GsonUtils.GsonToBean("{\"code\":200,\"msg\":\"success\",\"data\":{\"code\":8,\"desc\":\"价格发生变化!\",\"priceModels\":[{\"date\":\"2020-12-11\",\"salePrice\":25444,\"subPrice\":1272,\"subRatio\":500,\"dayType\":0}],\"remainRoomNum\":999}}",Result.class);//mtHotelOrderService.orderCheckApi(mtHotelOrderCheckParamVo);
//            }
//            if(i == 1){
//                resultCheck= GsonUtils.GsonToBean("{\"code\":200,\"msg\":\"success\",\"data\":{\"code\":8,\"desc\":\"价格发生变化!\",\"priceModels\":[{\"date\":\"2020-12-12\",\"salePrice\":25444,\"subPrice\":1272,\"subRatio\":500,\"dayType\":0}],\"remainRoomNum\":999}}",Result.class);//mtHotelOrderService.orderCheckApi(mtHotelOrderCheckParamVo);
//            }
//            if(i == 2){
//                resultCheck= GsonUtils.GsonToBean("{\"code\":200,\"msg\":\"success\",\"data\":{\"code\":8,\"desc\":\"价格发生变化!\",\"priceModels\":[{\"date\":\"2020-12-13\",\"salePrice\":25444,\"subPrice\":1272,\"subRatio\":500,\"dayType\":0}],\"remainRoomNum\":999}}",Result.class);//mtHotelOrderService.orderCheckApi(mtHotelOrderCheckParamVo);
//            }

            MtHotelOrderCheckVo childMtHotelOrderCheckVo = JacksonUtil.objToBean(resultCheck.getData(), MtHotelOrderCheckVo.class);
            if(resultCheck.getCode() == CommonConstants.SUCCESS && null != childMtHotelOrderCheckVo) {
                childCheckVoMap.put(startDate,childMtHotelOrderCheckVo);
                Integer checkCode = childMtHotelOrderCheckVo.getCode();
                remianRoomNum = childMtHotelOrderCheckVo.getRemainRoomNum();
                if(0 == checkCode || 8 == checkCode){
                    if(null != childMtHotelOrderCheckVo.getPriceModels() && childMtHotelOrderCheckVo.getPriceModels().size()>0){
                        MtHotelOrderCheckPricesVo pri = childMtHotelOrderCheckVo.getPriceModels().get(0);
                        priceModelsNew.add(pri);
                        allChildRealTotalPrice = allChildRealTotalPrice.add(new BigDecimal(pri.getSalePrice()).subtract(new BigDecimal(pri.getSubPrice())));//底价
                    }
                }else{
                    childErrorMsgMap.put(startDate,GsonUtils.GsonString(childMtHotelOrderCheckVo));
                }
            }
            startDate = nextDay;
        }
        if(null != childErrorMsgMap && childErrorMsgMap.size()>0){
            Result result = new Result();
            result.setCode(CommonConstants.REQUEST_ERROR);
            result.setData(GsonUtils.GsonString(childErrorMsgMap));
            result.setMsg("拆单分析：拆单存在子单下单前校验不通过："+GsonUtils.GsonString(childErrorMsgMap));
            return result;
        }else{
            //校验所有子单加起来的价格是否在允许亏损范围内可买
            Boolean isLoss = false;//是否是允许范围内的亏损单，需要推送钉钉
            String isLossMsg = "";
            String errorMsg = "";
            //构建一个主单信息的MtHotelOrderCheckParamVo
            MtHotelOrderCheckVo mtHotelOrderCheckVoNew = new MtHotelOrderCheckVo();
            mtHotelOrderCheckVoNew.setPriceModels(priceModelsNew);
            mtHotelOrderCheckVoNew.setCode(0);
            mtHotelOrderCheckVoNew.setRemainRoomNum(remianRoomNum);
            //mtHotelOrderCheckVo.setStatusModels();
            // 所有子单得到的价格日历 相加后  计算总价
            allChildRealTotalPrice = allChildRealTotalPrice.multiply(BigDecimal.valueOf(masterRoomnum));
            Map<String,Object> notEqCheckResult = mtHotelOrderDealService.notEqCheckPri(frontSwTotalPrice,allChildRealTotalPrice.intValue(),isLoss,isLossMsg,errorMsg,priceModelsNew,mtHotelOrderCheckVoNew,masterRoomnum);
            Integer checkcode = (Integer) notEqCheckResult.get("code");
            isLoss = (Boolean) notEqCheckResult.get("isLoss");
            isLossMsg = (String)notEqCheckResult.get("isLossMsg");
            errorMsg = (String)notEqCheckResult.get("errorMsg");
            if(BigDecimal.valueOf(checkcode).compareTo(BigDecimal.valueOf(CommonConstants.SUCCESS))!=0){
                //新订单总价 校验不通过
                Result result = new Result();
                result.setCode(CommonConstants.REQUEST_ERROR);
                result.setData(GsonUtils.GsonString(notEqCheckResult));
                result.setMsg("拆单分析：拆单后所有子单总价校验不通过："+errorMsg);
                return result;
            }else{
                if(isLoss){
                    return new Result(GsonUtils.GsonString(mtHotelOrderCheckVoNew),isLossMsg);
                }else{
                    //判断早餐是否正常
                    /*Result result = checkThisGoodsBreakfast(mtHotelId,String.valueOf(goodsId));
                    if(result.getCode()!=CommonConstants.SUCCESS){
                        notEqCheckResult = (String)result.getMsg();
                    }*/

                }
                return new Result(GsonUtils.GsonString(mtHotelOrderCheckVoNew),"success");
            }
        }

    }

    /**
     * 获取该单的子订单的尾部字母标识（判断该单是否存在子订单，如存在，则子订单的命名规则要顺位字母）
     * @return
     */
    public  String findOrderExsitChildGetChar(String masterOrderId){
        log.info("获取该单的子订单的尾部字母标识 进入 findOrderExsitChildGetChar");
        Example example = new Example(MtHotelOrderBooking.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("masterOrderId",masterOrderId);
        criteria.andEqualTo("split",2);
        List<MtHotelOrderBooking> mtHotelOrderBooking = mtHotelOrderBookingMapper.selectByExample(example);
        if(null != mtHotelOrderBooking && mtHotelOrderBooking.size()>0){
            log.info("获取该单的子订单的尾部字母标识 进入 mtHotelOrderBooking={}",GsonUtils.GsonString(mtHotelOrderBooking));
            String childOrderIndexId = mtHotelOrderBooking.get(0).getMtDistributorOrderId();
            log.info("获取该单的子订单的尾部字母标识 进入 return={}",childOrderIndexId.substring(childOrderIndexId.length()-3,childOrderIndexId.length()));
            return childOrderIndexId.substring(childOrderIndexId.length()-3,childOrderIndexId.length());
        }else{
            return null;
        }
    }

    /**
     * 取消  主订单所有的预订成功或预订中的子单
     *
     * 调用途径：1、splitBookingCancel     拆单采购过程中出现失败要进行回滚取消 --》该方法内不推钉钉
     *             2、 callbackOrderCancel 异步通知失败   要进行回滚取消  --》该方法内不推钉钉
     *             3、userApplyCancel 客户主动取消  ---》 要推送钉钉
     */
    @Override
    public Result cancelOtherChildSplitOrder(String master_mtDisOrderId_index,String checkNeedCancelMessage,String source) {
        log.info("取消主订单所有的已下单子单 ，进入取消操作cancelOtherChildSplitOrder");
        List<MtHotelOrderBooking> otherChildOrderList = mtHotelOrderService.getBookingChildOrderByMasterOrderId(master_mtDisOrderId_index);//预订中或预订成功的订单或已入住的订单
        MtHotelOrderBooking masterOrder = mtHotelOrderService.selectOneByMtDistributorOrderId(master_mtDisOrderId_index);
        Integer oper = null;
        String cancelErrorMsg = "";
        if(null != otherChildOrderList && otherChildOrderList.size()>0){
            String childOrderIds = "";
            for (MtHotelOrderBooking thisChildOrder:otherChildOrderList){
                childOrderIds +=thisChildOrder.getMtDistributorOrderId()+",";
            }
            if("callbackOrderCancel".equals(source)){
                oper =2;
                SendUtils.dingMsg("[FAILED-NOTICE-SPLIT] 拆单子单 美团异步通知预定失败了！程序将进行其他已预订子单自动批量取消操作.......请关注取消情况.....", hotel.base.oversea.utils.DateUtil.getCurrTime()+" 主单订单号="+master_mtDisOrderId_index+" 该主单拆单过"+otherChildOrderList.size()+"笔子单 子单订单号="+childOrderIds,MessageEnums.genre.REFUDE_ERROR.getCode(),restTemplate);
            }else if("splitBookingCancel".equals(source)){
                oper =2;
                SendUtils.dingMsgNotLog("[SPLIT-BOOKING-ERROR] 拆单采购中出现子单'预下单'失败，程序将对预订中或成功的子单进行回滚取消操作！请关注子单取消情况 ",DateUtil.getCurrTime()+" 校验内容："+checkNeedCancelMessage+" 该主单拆单过"+otherChildOrderList.size()+"笔子单 子单订单号="+childOrderIds,MessageEnums.genre.REFUDE_ERROR.getCode(),restTemplate);
            }else if("userApplyCancel".equals(source)){
                oper =1;
                SendUtils.dingMsgNotLog("[SPLIT-BOOKING-ERROR] 用户申请取消订单为拆单订单，程序将对已预下单成功的子单进行回滚取消操作！请关注子单取消情况 ",DateUtil.getCurrTime()+" 校验内容："+checkNeedCancelMessage+" 该主单拆单过"+otherChildOrderList.size()+"笔子单 子单订单号="+childOrderIds,MessageEnums.genre.REFUDE_ERROR.getCode(),restTemplate);
            }else{
                SendUtils.dingMsgNotLog("[SPLIT-BOOKING-ERROR][未识别的source="+source+"]程序将对已预下单成功的子单进行回滚取消操作！请关注子单取消情况 ",DateUtil.getCurrTime()+" 校验内容："+checkNeedCancelMessage+" 该主单拆单过"+otherChildOrderList.size()+"笔子单 子单订单号="+childOrderIds,MessageEnums.genre.REFUDE_ERROR.getCode(),restTemplate);
            }

            Integer cancelSuccess = 0;
            Integer cancelErrorCount = 0;
            for (MtHotelOrderBooking thisChildOrder:otherChildOrderList){
                String childOrderIndexId = thisChildOrder.getMtDistributorOrderId();
                MtHotelOrderCancelParamVo mtHotelOrderCancelParamVo = new MtHotelOrderCancelParamVo();
                mtHotelOrderCancelParamVo.setDistributorOrderId(thisChildOrder.getMtDistributorOrderId());
                mtHotelOrderCancelParamVo.setMtOrderId(Long.valueOf(thisChildOrder.getMtOrderId()));
                Result<Object> thisChildCancel =  mtHotelOrderService.orderCancelApi(mtHotelOrderCancelParamVo);
                if(thisChildCancel.getCode()!=CommonConstants.SUCCESS){
                    //子单取消失败
                    SendUtils.dingMsgNotLog("[SPLIT-CANCEL-ERROR] 子单取消失败了！请人工处理",DateUtil.getCurrTime()+" 子单订单号："+thisChildOrder.getMtDistributorOrderId()+" 主单订单号："+master_mtDisOrderId_index+" 内容："+GsonUtils.GsonString(thisChildCancel),MessageEnums.genre.REFUDE_ERROR.getCode(),restTemplate);

                }else{
                    MtHotelOrderCancelVo mtHotelOrderCancelApiResponseVo = (MtHotelOrderCancelVo)thisChildCancel.getData();
                    /**
                     * 0 取消成功
                     * 1 系统繁忙
                     * 2 取消失败（超过最晚可取消时间；用户已入住等原因）
                     * 3 订单号不存在
                     * 4 取消失败，产品不允许取消
                     * 5 订单取消中
                     * 10 订单已经确认
                     * 20 其它
                     */
                    if(0==mtHotelOrderCancelApiResponseVo.getCode()){
                        cancelSuccess +=1;
                        //取消成功
                        SendUtils.dingMsgNotLog("[SPLIT-CANCEL] 子单取消成功 ",DateUtil.getCurrTime()+" 子单订单号："+thisChildOrder.getMtDistributorOrderId()+" 主单订单号："+master_mtDisOrderId_index+" 内容："+GsonUtils.GsonString(thisChildCancel),MessageEnums.genre.REFUDE_ERROR.getCode(),restTemplate);
                        mtHotelOrderService.updateOneChildOrderStatus(master_mtDisOrderId_index,childOrderIndexId,MtHotelEnums.orderStateEnum.CANCELSUCCSS.getCode(),null);
                    }else  if(5==mtHotelOrderCancelApiResponseVo.getCode()){
                        //取消中
                        SendUtils.dingMsgNotLog("[SPLIT-CANCEL] 子单取消中，等待异步通知 ",DateUtil.getCurrTime()+" 子单订单号："+thisChildOrder.getMtDistributorOrderId()+" 主单订单号："+master_mtDisOrderId_index+" 内容："+GsonUtils.GsonString(thisChildCancel),MessageEnums.genre.REFUDE_ERROR.getCode(),restTemplate);
                        mtHotelOrderService.updateOneChildOrderStatus(master_mtDisOrderId_index,childOrderIndexId,MtHotelEnums.orderStateEnum.CANCELING.getCode(),null);
                    }else{
                        cancelErrorCount +=1;
                        SendUtils.dingMsgNotLog("[SPLIT-CANCEL] 子单取消失败了！请人工处理 ",DateUtil.getCurrTime()+" 子单订单号："+thisChildOrder.getMtDistributorOrderId()+" 主单订单号："+master_mtDisOrderId_index+" 内容："+GsonUtils.GsonString(thisChildCancel),MessageEnums.genre.REFUDE_ERROR.getCode(),restTemplate);
                        mtHotelOrderService.updateOneChildOrderStatus(master_mtDisOrderId_index,childOrderIndexId,MtHotelEnums.orderStateEnum.CANCELFAILED.getCode(),null);
                        cancelErrorMsg += " 已下子单"+thisChildOrder.getMtDistributorOrderId()+",取消失败"+GsonUtils.GsonString(thisChildCancel);
                    }
                }
            }
            if(cancelSuccess>0){
                //存在取消成功，更新取消成功次数
                mtHotelOrderService.updateMasterOrderCancelSuccessCount(master_mtDisOrderId_index,childOrderIds,cancelSuccess);
            }
            if(cancelSuccess==otherChildOrderList.size()){
                //全部取消成功
                if("userApplyCancel".equals(source)){
                    checkUserApplyCancelNoticeSw(masterOrder.getSwOrderId(),source);
                    mtHotelOrderService.updateMasterOrderOper(master_mtDisOrderId_index,MtHotelEnums.orderStateEnum.CANCELSUCCSS.getCode(),oper);
                }else{
                    //全部取消成功，修改主单状态为 失效单 --》用户申请的不可改为失效
                    mtHotelOrderService.updateOneMasterSplitOrderIsFailed(master_mtDisOrderId_index,null,oper);
                }
            }else{
                //部分取消成功    取消中   取消失败
                if(cancelErrorCount>0){
                    //存在取消失败
                    mtHotelOrderService.updateMasterOrderCancelFailedCount(master_mtDisOrderId_index,childOrderIds,cancelErrorCount);
                    if("userApplyCancel".equals(source)){
                        //是用户申请的取消，有一单存在取消失败，就直接修改主单为取消失败--》异步可能会重复修改取消失败 如果异步有通知其他子单
                        mtHotelOrderService.updateMasterOrderOper(master_mtDisOrderId_index,MtHotelEnums.orderStateEnum.CANCELFAILED.getCode(),oper);
                        //存在取消失败就修改携程pool
                        mtHotelOrderService.requestUpdateStateOrderPool("美团通知订单取消失败",masterOrder.getSwOrderId(),MtHotelEnums.orderStateEnum.CANCELFAILED.getCode(),42,source,null,null,null);
                    }else{
                        //非用户的取消
                        if(cancelErrorCount==otherChildOrderList.size()) {
                            //全部存在取消失败，直接将主单改为失效，然后让人工处理取消失败单
                            mtHotelOrderService.updateOneMasterSplitOrderIsFailed(master_mtDisOrderId_index,null,oper);
                        }else{
                            //其他需要异步通知，然后在异步通知等所有单子通知完后修改主单为失效
                            //....
                            return new Result("waitCallback",CommonConstants.SUCCESS);
                        }
                    }
                    if(cancelErrorCount==otherChildOrderList.size()) {
                        //全部取消失败
                        //全部存在取消失败，直接将主单改为失效，然后让人工处理取消失败子单
                        mtHotelOrderService.updateOneMasterSplitOrderIsFailed(master_mtDisOrderId_index,null,oper);

                    }

                }else{
                    //都是取消中
                    //让异步通知判断处理 //修改主单状态.........--->>如果上面for发起取消中过程中 取消异步通知就请求过来？？？？？--》》master订单还在forupdate当中-->该问题不会影响

                    return new Result("waitCallback",CommonConstants.SUCCESS);//外部根据msg判断需要解锁主单-->外部不修改为失效单，等所有取消单都异步通知过来了，再改为失效单
                }
            }
        }else{
            log.error("直接，该主订单没有子订单"+master_mtDisOrderId_index);////子单采购失败或者确认为不再采购的都state改为1 --->所以此时会出现没有采购过的子单，因为第一单就预下单失败了
            //SendUtils.dingMsgNotLog("[SPLIT-BOOKING-ERROR] 首个子单'预下单'失败，当前停止子单采购！无可需要做取消操作的子单，请人工处理主单！ ",DateUtil.getCurrTime()+" 校验失败："+null,MessageEnums.genre.DELAYED_ORDER.getCode(),restTemplate);
            //没有需取消的子单，直接修改主单和pool单
            Result checkua =  checkUserApplyCancelNoticeSw(masterOrder.getSwOrderId(),source);
            SendUtils.dingMsgNotLog("[CANCEL-SUCCESS-NONE-CHILD] 主单没有预订的子单，取消成功 ", DateUtil.getCurrTime()+" 订单号："+master_mtDisOrderId_index+" 创建订单时间："+ DateUtil.formatDate(masterOrder.getCreateTime(),"yyyy-MM-dd HH:mm:ss"),MessageEnums.genre.REFUDE_ERROR.getCode(),restTemplate);
            if("userApplyCancel".equals(source)){
                mtHotelOrderService.updateMasterOrderOper(master_mtDisOrderId_index,MtHotelEnums.orderStateEnum.CANCELSUCCSS.getCode(),oper);
            }else{
                //修改主单状态为 失效单--》用户申请的不可改为失效
                mtHotelOrderService.updateOneMasterSplitOrderIsFailed(master_mtDisOrderId_index,null,oper);
            }
        }
        if(ObjectUtils.isEmpty(cancelErrorMsg)){
            return new Result();
        }else{
            return new Result(cancelErrorMsg,CommonConstants.REQUEST_ERROR);
        }


    }

    private Result checkUserApplyCancelNoticeSw(String swOrderId,String source){
        if("userApplyCancel".equals(source)){
            //通知携程处理订单
            OperateDltOrderVo operateDltOrderVo = new OperateDltOrderVo();
            operateDltOrderVo.setOrderId(swOrderId);
            operateDltOrderVo.setOperaterType(11);//11-接受取消,
            Result resultDeal = mtHotelOrderService.operaterDltOrder(operateDltOrderVo);//通知携程订单操作接口 确认订单
            if(resultDeal.getCode()!= CommonConstants.SUCCESS){
                log.error("[CANCEL-SUCCESS-NONE-CHILD] 拆单订单直接'取消'成功，该主单还未预订子单 通知处理订单接口-取消订单-返回失败！异步通知是成功的！ [884-operaterDltOrder]：resultDeal={}", JSON.toJSONString(resultDeal));
                if(null != resultDeal.getMsg() && !resultDeal.getMsg().toString().contains("已处理")){
                    SendUtils.dingMsgNotLog("[CANCEL-SUCCESS-NONE-CHILD] 拆单订单直接'取消'成功，该主单还未预订子单，但携程处理订单接口-取消订单-返回失败！ ","携程处理接口失败返回="+ JSON.toJSONString(resultDeal)+" 请求参数："+GsonUtils.GsonString(operateDltOrderVo),MessageEnums.genre.REFUDE_ERROR.getCode(),restTemplate);
                }
                //取消成功 更新pool表两个字段  meituanOrderState+系统状态字段，不需要推送携程
                Boolean updatePoolResult = mtHotelOrderService.requestUpdateStateOrderPool("拆单订单直接取消成功",swOrderId,MtHotelEnums.orderStateEnum.CANCELSUCCSS.getCode(),12,source,null,null,null);//系统接受取消失败改为12携程人工处理订单
            }else{
                //取消成功 更新pool表两个字段  meituanOrderState+系统状态字段，不需要推送携程
                Boolean updatePoolResult = mtHotelOrderService.requestUpdateStateOrderPool("拆单订单直接取消成功",swOrderId,MtHotelEnums.orderStateEnum.CANCELSUCCSS.getCode(),4,source,null,null,null);//系统接受取消成功已拒绝 4
            }
            return new Result();
        }
        return new Result("",CommonConstants.REQUEST_ERROR);
    }

    /**
     * 子订单  采购  美团api接口预下单
     * @param mtHotelOrderCheckVo
     * @param mtDisOrderId_index
     * @param masterOrderId
     * @return
     */
    private Result bookingSplit(MtHotelOrderCheckVo mtHotelOrderCheckVo,String mtDisOrderId_index,String masterOrderId,String mtHotelId,Integer goodsId,String checkinDate,String checkoutDate,Integer roomnum,String personNames,String contactName){
        //预约下单
        log.info("进入子单预下单 bookingSplit，mtDisOrderId_index={},masterOrderId={}",mtDisOrderId_index,masterOrderId);
/*        //参数
        String mtHotelId = mtHotelOrderJobDealVo.getMtHotelId();//美团酒店id
        Integer goodsId = mtHotelOrderJobDealVo.getGoodsId();//美团产品id
        String checkinDate = mtHotelOrderJobDealVo.getCheckinDate();//日期格式 yyyy-MM-dd
        String checkoutDate = mtHotelOrderJobDealVo.getCheckoutDate();
        Integer roomnum = mtHotelOrderJobDealVo.getRoomnum();*/

        //美团下单前校验返回最新价格 priceModels
        List<MtHotelOrderCheckPricesVo> priceModels = mtHotelOrderCheckVo.getPriceModels();
        int mtShowSaleTotalPrice = 0;//美团订单市场价总价
        int subPrice = 0;//美团分销商佣金
        for (MtHotelOrderCheckPricesVo priceModel : priceModels) {
            //美团采购订单总价 * 房间数
            mtShowSaleTotalPrice = mtShowSaleTotalPrice + (priceModel.getSalePrice() * roomnum);
            //每间佣金 * 房间数
            subPrice = subPrice + (priceModel.getSubPrice() * roomnum);
        }
        Integer costTotalPrice = BigDecimal.valueOf(mtShowSaleTotalPrice).subtract(BigDecimal.valueOf(subPrice)).intValue();//结算采购成本总价=总价减去分销商佣金

        MtHotelOrderBookingParamVo mtHotelOrderBookingParamVo = new MtHotelOrderBookingParamVo();
        mtHotelOrderBookingParamVo.setDistributorOrderId(mtDisOrderId_index);
        mtHotelOrderBookingParamVo.setHotelId(mtHotelId);
        mtHotelOrderBookingParamVo.setGoodsId(String.valueOf(goodsId));
        mtHotelOrderBookingParamVo.setPersonNames(personNames);
        mtHotelOrderBookingParamVo.setContactName(contactName);
        //todo 携程订单联系人电话暂无,使用400号码
        mtHotelOrderBookingParamVo.setContactPhone(StringUtil.getQueuePhone(redisTemplate));
        mtHotelOrderBookingParamVo.setMtHotelOrderCheckVo(mtHotelOrderCheckVo);
        mtHotelOrderBookingParamVo.setCheckinDate(checkinDate);
        mtHotelOrderBookingParamVo.setCheckoutDate(checkoutDate);
        mtHotelOrderBookingParamVo.setRoomNum(roomnum);
        mtHotelOrderBookingParamVo.setTotalPrice(mtShowSaleTotalPrice);
        mtHotelOrderBookingParamVo.setSettlePrice(costTotalPrice);

        log.info("子单  调用下单api booking请求参数={}", JSON.toJSONString(mtHotelOrderBookingParamVo));
        Result bookingResult = mtHotelOrderService.orderBookingSplitOrder(mtHotelOrderBookingParamVo,masterOrderId);
        log.info("子单  调用下单api返回={}", JSON.toJSONString(bookingResult));
        return bookingResult;
    }


    /**
     * 美团异步通知时 调用
     * 判断异步通知订单是否为拆单子单
     * @param childMtOrder
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Result checkIsSplitChildOrder(MtHotelOrderBooking childMtOrder, Integer childOrderStatus, String source, MtHotelOrderStateHistory stateHistory) {
        /**
         * 当前主单和pool表 订单状态为 人工处理拆单状态，，如果所有子单预订成功才需要改状态，其他不做修改
         */

        if(null != childMtOrder){
            Integer split = childMtOrder.getSplit();//split = 1 时为拆单主单 ，，split=2 时为拆单子单，，当为拆单子单时masterOrderId=原订单mtDistributorOrderId，swOrderId为null
            if(null != split && 2== split){//子单
                String child_distributorOrderId_index = childMtOrder.getMtDistributorOrderId();
                String masterOrderId = childMtOrder.getMasterOrderId();
                MtHotelOrderBooking masterMtOrder = mtHotelOrderService.selectOneByMtDistributorOrderId(masterOrderId);
                if(null  != masterMtOrder){
                    MtHotelOrderBooking masterMtOrderForUpdate = mtHotelOrderService.selectOneByDisOrderIdForUpdate(masterOrderId);//锁单获取主单信息
                    if(null != masterMtOrderForUpdate){
                        //当前为拆单子单
                        if(MtHotelEnums.orderStateEnum.FAILED.getCode()==childOrderStatus || MtHotelEnums.orderStateEnum.BOOKINGSUCCSS.getCode()==childOrderStatus
                                || MtHotelEnums.orderStateEnum.CANCELSUCCSS.getCode()==childOrderStatus || MtHotelEnums.orderStateEnum.CANCELFAILED.getCode()==childOrderStatus){
                            MtHotelOrderBooking childOrderBookingForUpdate = mtHotelOrderService.selectOneByDisOrderIdForUpdate(child_distributorOrderId_index);//锁单获取订单信息
                            if(null != childOrderBookingForUpdate) {
                                //进入状态业务处理
                                callbackCheckThisOrderStatus(masterMtOrder,source,childOrderStatus,child_distributorOrderId_index,stateHistory);//内部判断进行合理释放锁update主单和子单
                            }else{
                                //主单释放锁
                                mtHotelOrderService.updateStateOrderBookingByDistributorOrderId(masterOrderId,masterMtOrder.getMtOrderState(),null,null,null);
                            }
                        }else{
                            //其他状态  已入住等状态，
                            if(MtHotelEnums.orderStateEnum.IN.getCode()==childOrderStatus){
                                ////////////////////////requestUpdateStateOrderPool("美团通知订单用户已入住",MtHotelEnums.orderStateEnum.IN.getCode(),null,source,null, null,null);
                                SendUtils.dingMsgNotLog("[CHECKIN-NOTICE-SPLIT]拆单子单,用户已入住 ", DateUtil.getCurrTime()+" 子单订单号："+child_distributorOrderId_index+" 主单订单号："+masterOrderId,MessageEnums.genre.MT_ORDER_OPERA.getCode(),restTemplate);
                            }
                            //主单释放锁
                            mtHotelOrderService.updateStateOrderBookingByDistributorOrderId(masterOrderId,masterMtOrder.getMtOrderState(),null,null,null);
                        }

                        return new Result("",CommonConstants.SUCCESS);
                    }else{
                        SendUtils.dingMsgNotLog("[ERROR-SPLIT]异步通知拆单子单 但程序获取主单信息失败，请人工核实！！ ", DateUtil.getCurrTime() + " 子单订单号：" + child_distributorOrderId_index +" 推送内容："+stateHistory.getClassJson(), MessageEnums.genre.DELAYED_ORDER.getCode(), restTemplate);
                    }
                }else{
                    SendUtils.dingMsgNotLog("[ERROR-SPLIT]异步通知拆单子单 但程序获取主单信息失败，请人工核实！！ ", DateUtil.getCurrTime() + " 子单订单号：" + child_distributorOrderId_index +" 推送内容："+stateHistory.getClassJson(), MessageEnums.genre.DELAYED_ORDER.getCode(), restTemplate);
                }
                return new Result();
            }else{
                return new Result("",CommonConstants.REQUEST_ERROR);//当前非拆单
            }
        }else{
            return new Result("",CommonConstants.REQUEST_ERROR);//当前非拆单
        }
    }

    private void callbackCheckThisOrderStatus(MtHotelOrderBooking masterMtOrder, String source, Integer childOrderStatus, String child_distributorOrderId_index, MtHotelOrderStateHistory stateHistory) {
        String masterOrderId = masterMtOrder.getMasterOrderId();
        String masterSwOrderId = masterMtOrder.getSwOrderId();

        String content = "";
        Integer splitDays = masterMtOrder.getSplitDays();
        if (null != source && source.equals("主动查询美团定时器")) {
            content = ",当前订单为主动查询订单定时器处理";
        }
        if (childOrderStatus == MtHotelEnums.orderStateEnum.FAILED.getCode()) {
            //中断其他子单预订操作，并做回滚取消操作：setRedis 中断预订标识
            redisService.setUnit("split_booking_submit_stop"+masterOrderId,1,15L,TimeUnit.SECONDS);


            //修改子单（释放锁），回滚内部无需操作当前该单（内部只操作 20  21  50 的订单）
            mtHotelOrderService.updateStateOrderBookingByDistributorOrderId(child_distributorOrderId_index,childOrderStatus,null,null,null);

            //回滚取消
            Result cancelRes = this.cancelOtherChildSplitOrder(masterOrderId,null,"callbackOrderCancel");
            if(cancelRes.getCode()==CommonConstants.SUCCESS && null != cancelRes.getMsg() && cancelRes.getMsg().toString().contains("waitCallback")){
                //当前解锁主单  等待异步通知所有取消单，当前不将主单改为失效单，等异步通知判断cancelSuccessCount等于days才改为失效单
                mtHotelOrderService.updateStateOrderBookingByDistributorOrderId(masterOrderId,masterMtOrder.getMtOrderState(),null,null,null);
            }
            //修改携程pool
            mtHotelOrderService.requestUpdateStateOrderPool("美团通知订单失败",masterSwOrderId,childOrderStatus,42,source,null,null,null);//美团取消失败，系统状态改为12人工处理


        } else if (childOrderStatus == MtHotelEnums.orderStateEnum.BOOKINGSUCCSS.getCode()) {
            Integer splitSuccessCount = masterMtOrder.getSplitSuccessCount();
            //判断是否都预订成功根据split_success_count，修改主单的子单预订成功数量字段：需预订成功子单数量根据字段split_days
            Integer childOrderDiff = new BigDecimal(splitDays).subtract(new BigDecimal(splitSuccessCount)).intValue();
            Integer thisChildOrderIndexSuccessCount = splitSuccessCount+1;
            if(childOrderDiff==1){
                SendUtils.dingMsgNotLog("[SUCCESS-SPLIT]第"+thisChildOrderIndexSuccessCount+"笔子单 预定成功 为最后一笔子单 ", DateUtil.getCurrTime() + "：" +" 主单订单号："+masterOrderId+" 子单订单号："+child_distributorOrderId_index+ content, MessageEnums.genre.ORDER_NOTICY.getCode(), restTemplate);

                SendUtils.dingMsgNotLog("[SPLIT-SUCCESS] 所有子单完成采购 ^ 0 ^ ^ 0 ^  ",DateUtil.getCurrTime()+
                        " 连住主订单号："+masterOrderId+" 入住离店时间："+masterMtOrder.getMtCheckinDate()+"+"+masterMtOrder.getMtCheckoutDate()+" 房间数："+masterMtOrder.getMtRoomNum(),MessageEnums.genre.ORDER_NOTICY.getCode(),restTemplate);

            }else{
                SendUtils.dingMsgNotLog("[SUCCESS-SPLIT]第"+thisChildOrderIndexSuccessCount+"笔子单 预定成功 ", DateUtil.getCurrTime() + "：" +" 主单订单号："+masterOrderId+" 子单订单号："+child_distributorOrderId_index+ content, MessageEnums.genre.ORDER_NOTICY.getCode(), restTemplate);
            }
            if(childOrderDiff==1){
                if(null != redisService.get("split_booking_submit_stop"+masterOrderId)){
                    log.info("split_booking_submit_stop异步通知最后一步预定成功订单  split_booking_submit_stop 1、用户申请取消主单   2、异步通知预订失败   ---------》》 不通知携程");
                }else{

                    //当前为最后一单子单异步通知预订成功，，则所有子单都预订成功：可操作：1、推送通知携程和修改pool表  2、修改美团主订单状态
                    //修改pool表订单状态
                    Boolean updatePoolResult = mtHotelOrderService.requestUpdateStateOrderPool(DateUtil.getCurrTime()+" 美团通知订单预订成功",masterSwOrderId,childOrderStatus,1,source,1,null,null);//1：已确认（携程订单校验通过并接受订单)
                    if(!updatePoolResult){
                        //保存日志
                        MtHotelOrderStateHistory stateHistory2 = new MtHotelOrderStateHistory();
                        stateHistory2.setMtDistributorOrderId(masterOrderId);
                        stateHistory2.setSwOrderId(masterSwOrderId);
                        stateHistory2.setMtOrderId(masterMtOrder.getMtOrderId());
                        stateHistory2.setStatusCode(-1);//人工关注
                        stateHistory2.setStatusDesc("拆单最后一笔预订完成-美团成功但系统pool更新失败 美团为最新状态21人工关注！：desc="+stateHistory.getStatusDesc()+",orderStatus="+childOrderStatus);
                        stateHistory2.setMtHotelId(null);
                        stateHistory2.setMtGoodsId(null);
                        stateHistory2.setMethod(stateHistory.getMethod());
                        stateHistory2.setMethodName(MtHotelEnums.apiMethodEnum.METHOD_HOTEL_ORDER_STATE_CALLBACK.getName());
                        stateHistory2.setClassJson(stateHistory.getClassJson());
                        stateHistory2.setMtOrderState(childOrderStatus);
                        mtHotelOrderService.saveOrderStateHistory(stateHistory2);
                    }

                    //mtHotelOrderService.updateStateOrderBookingByDistributorOrderId(child_distributorOrderId_index,orderStatus,"预订成功",null,null);
                    redisTemplate.opsForValue().set(MeituanConstants.REDIS_KEY_HEAD_MT_ORDER_JOB_ING_VALUE_ORDER_ID+child_distributorOrderId_index,masterSwOrderId,30, TimeUnit.SECONDS);

                    //通知携程 接收订单 --》通知主单
                    OperateDltOrderVo operateDltOrderVo = new OperateDltOrderVo();
                    operateDltOrderVo.setOrderId(masterSwOrderId);
                    operateDltOrderVo.setOperaterType(0);//操作类型 0 下单成功，接受订单
                    operateDltOrderVo.setConfirmType(1);//确认方式 1 按入住人姓名
                    Result resultDeal = mtHotelOrderService.operaterDltOrder(operateDltOrderVo);//通知携程订单操作接口 确认订单
                    if(resultDeal.getCode()!= CommonConstants.SUCCESS){
                        log.error("[SUCCESS-NOTICE-FAILED-SWITCHS-SPLIT] 通知处理订单接口-确认订单-返回失败！异步通知是成功的！ [884-operaterDltOrder]：resultDeal={},apireturn={}", JSON.toJSONString(resultDeal),stateHistory.getClassJson());
                        if(null != resultDeal.getMsg() && !resultDeal.getMsg().toString().contains("已处理")){
                            SendUtils.dingMsgNotLog("[SUCCESS-NOTICE-FAILED-SWITCHS-SPLIT]子单最后一笔预订成功，通知携程接受订单，但携程处理订单接口-确认订单-返回失败！ ","携程处理接口失败返回="+ JSON.toJSONString(resultDeal)+",携程订单号="+masterSwOrderId,MessageEnums.genre.DELAYED_ORDER.getCode(),restTemplate);
                        }
                    }
                }
                //子单释放锁
                mtHotelOrderService.updateStateOrderBookingByDistributorOrderId(child_distributorOrderId_index,childOrderStatus,null,null,null);
                //主单释放锁 更新successcount+日志
                mtHotelOrderService.updateMasterOrderSuccessSplitCount(masterOrderId,child_distributorOrderId_index,thisChildOrderIndexSuccessCount,splitDays);

            }else{
                //子单释放锁
                mtHotelOrderService.updateStateOrderBookingByDistributorOrderId(child_distributorOrderId_index,childOrderStatus,null,null,null);
                //主单释放锁  更新成功数量splitCount +  count日志
                mtHotelOrderService.updateMasterOrderSuccessSplitCount(masterOrderId,child_distributorOrderId_index,thisChildOrderIndexSuccessCount,splitDays);
                //异步通知外部已经保存子单日志

            }

            log.info("美团异步通知预订成功!~  distributorOrderId={}", child_distributorOrderId_index);
        } else if (childOrderStatus == MtHotelEnums.orderStateEnum.CANCELFAILED.getCode()) {//已涉及update
            SendUtils.dingMsgNotLog("[CANCEL-FAILED-NOTICE-SPLIT]拆单子单 美团订单酒店'取消'失败！请及时处理！", DateUtil.getCurrTime() + "：" + stateHistory.getClassJson() + content+" 主单订单号："+masterOrderId+" 子单订单号："+child_distributorOrderId_index, MessageEnums.genre.REFUDE_ERROR.getCode(), restTemplate);
            log.info("FAILED~拆单子单异步通知订单'取消'失败！请及时处理！  {}", stateHistory.getClassJson());

            //有一单取消失败，就修改携程订单为取消失败和主单改为取消失败（这时候可能还有其他子单还在异步通知取消结果）
            Integer cancelFailedCount = masterMtOrder.getCancelFailedCount();
            Integer cancelSuccessCount = masterMtOrder.getCancelSuccessCount();
            BigDecimal operCancelCount = new BigDecimal(cancelFailedCount).add(new BigDecimal(cancelSuccessCount));
            Integer oper = masterMtOrder.getOper();
            Integer childOrderCancelDiff = new BigDecimal(splitDays).subtract(operCancelCount).intValue();

            if(null != oper && oper==1){
                if(childOrderCancelDiff==1) {//用户申请的取消并且是处理了最后一单取消单后 （succes+failed）--->>>不然如果还有其他取消单在异步通知但是主单已经是state=1失效状态，则子单会进不来
                    //用户取消，更新主单取消状态
                    mtHotelOrderService.updateMasterOrderOper(masterOrderId,MtHotelEnums.orderStateEnum.CANCELFAILED.getCode(),null);
                }
                //用户申请的失败有一单失败就通知携程  6 美团取消失败  --》这个地方可能会超过2次修改
                mtHotelOrderService.requestUpdateStateOrderPool("美团通知订单取消失败",masterSwOrderId,MtHotelEnums.orderStateEnum.CANCELFAILED.getCode(),6,source,null,null,null);
            }else{
                //修改主单状态为失效  (有一单失败就修改主单为失效)
                mtHotelOrderService.updateOneMasterSplitOrderIsFailed(masterOrderId,child_distributorOrderId_index,null);
                //修改携程pool
                mtHotelOrderService.requestUpdateStateOrderPool("美团通知订单取消失败",masterSwOrderId,MtHotelEnums.orderStateEnum.CANCELFAILED.getCode(),42,source,null,null,null);//美团42拆单人工处理
            }


            //在该结尾处更新主单失败取消数量
            mtHotelOrderService.updateMasterOrderCancelFailedCount(masterOrderId,child_distributorOrderId_index,cancelFailedCount+1);

            //更新子单取消状态取消失败
            mtHotelOrderService.updateOneChildOrderStatus(masterOrderId,child_distributorOrderId_index,MtHotelEnums.orderStateEnum.CANCELFAILED.getCode(),null);


        } else if (childOrderStatus == MtHotelEnums.orderStateEnum.CANCELSUCCSS.getCode()) {//已涉及update
            //判断取消成功订单数量，是最后一单的话，修改主单位取消成功（判断若为用户申请取消则推送携程取消接收）
            Integer cancelSuccessCount = masterMtOrder.getCancelSuccessCount();
            Integer oper = masterMtOrder.getOper();
            Integer childOrderCancelDiff = new BigDecimal(splitDays).subtract(new BigDecimal(cancelSuccessCount)).intValue();
            Integer thisChildCancelOrderIndex = cancelSuccessCount+1;
            if(childOrderCancelDiff==1){//如果中途异步通知取消失败，则cancelsuccesscount不会等于days，不会走到这一步，将不会触发推送携程取消接收，要人工处理
                SendUtils.dingMsg("[CANCEL-SUCCESS-NOTICE-SPLIT]最后一笔 拆单子单 美团订单'取消'成功 ", DateUtil.getCurrTime()+"："+" 主单订单号："+masterOrderId+" 子单订单号："+child_distributorOrderId_index+content,MessageEnums.genre.REFUDE_ERROR.getCode(),restTemplate);
                //最后一单取消成功
                if(null != oper && oper==1){//用户申请的取消推送携程取消接收
                    checkUserApplyCancelNoticeSw(masterSwOrderId,"userApplyCancel");
                    //用户取消，更新主单取消状态
                    mtHotelOrderService.updateMasterOrderOper(masterOrderId,MtHotelEnums.orderStateEnum.CANCELSUCCSS.getCode(),null);
                }
            }else{
                SendUtils.dingMsg("[CANCEL-SUCCESS-NOTICE-SPLIT]拆单子单 美团订单'取消'成功 ", DateUtil.getCurrTime()+"："+" 主单订单号："+masterOrderId+" 子单订单号："+child_distributorOrderId_index+content,MessageEnums.genre.REFUDE_ERROR.getCode(),restTemplate);
            }
            //在该结尾处更新主单成功取消数量
            mtHotelOrderService.updateMasterOrderCancelSuccessCount(masterOrderId,child_distributorOrderId_index,thisChildCancelOrderIndex);

            //更新子单取消状态
            mtHotelOrderService.updateOneChildOrderStatus(masterOrderId,child_distributorOrderId_index,MtHotelEnums.orderStateEnum.CANCELSUCCSS.getCode(),null);


            log.info("[CANCEL-SUCCESS-SPLIT]拆单子单 订单'取消'成功 ",stateHistory.getClassJson());
        }

    }

    /**
     * 用户申请取消，判断是否为拆单主单取消
     * @param masterOrder
     * @return
     */
    @Override
    public Result checkIsMasterOrderApplyCancel(MtHotelOrderBooking masterOrder) {
        if(null != masterOrder && null != masterOrder.getSplit() && 1==masterOrder.getSplit()){//当前为拆单主单 的用户取消操作
            String master_distributorOrderId_index = masterOrder.getMtDistributorOrderId();
            log.info("拆单主单进行取消："+master_distributorOrderId_index);
            MtHotelOrderBooking masterOrderForUpdate = mtHotelOrderService.selectOneByDisOrderIdForUpdate(master_distributorOrderId_index);
            if(null != masterOrderForUpdate){

                //多子单预下单for循环中将被break
                redisService.setUnit("split_booking_submit_stop"+masterOrder.getMtDistributorOrderId(),1,15L,TimeUnit.SECONDS);

                MtHotelOrderCancelVo mtHotelOrderCancelApiResponseVo = new MtHotelOrderCancelVo();
                mtHotelOrderCancelApiResponseVo.setCode(5);//5 订单取消中
                mtHotelOrderCancelApiResponseVo.setDistributorOrderId(master_distributorOrderId_index);
                mtHotelOrderCancelApiResponseVo.setMtOrderId(Long.valueOf(master_distributorOrderId_index));

                //update进行释放锁
                mtHotelOrderService.updateMasterOrderOper(master_distributorOrderId_index,MtHotelEnums.orderStateEnum.CANCELING.getCode(),1);

                //保存订单状态日志
                MtHotelOrderStateHistory stateCancelHistory = new MtHotelOrderStateHistory();
                stateCancelHistory.setMtDistributorOrderId(master_distributorOrderId_index);
                stateCancelHistory.setSwOrderId(masterOrder.getSwOrderId());
                stateCancelHistory.setMasterOrderId(masterOrder.getMasterOrderId());
                stateCancelHistory.setMtHotelId(null);
                stateCancelHistory.setMtGoodsId(null);
                stateCancelHistory.setMtOrderId(String.valueOf(masterOrder.getMtOrderId()));
                stateCancelHistory.setMethod(MtHotelEnums.apiMethodEnum.METHOD_HOTEL_ORDER_CANCEL.getMethod());
                stateCancelHistory.setMethodName(MtHotelEnums.apiMethodEnum.METHOD_HOTEL_ORDER_CANCEL.getName());
                stateCancelHistory.setStatusCode(mtHotelOrderCancelApiResponseVo.getCode());
                stateCancelHistory.setStatusDesc(mtHotelOrderCancelApiResponseVo.getDesc());
                stateCancelHistory.setRemark("程序判断为主单取消，直接返回取消中，等待程序异步通知");
                stateCancelHistory.setClassName("MtHotelOrderCancelVo");
                stateCancelHistory.setClassJson(JSONObject.toJSONString(mtHotelOrderCancelApiResponseVo));
                stateCancelHistory.setMtOrderState(MtHotelEnums.orderStateEnum.CANCELING.getCode());
                mtHotelOrderService.saveOrderStateHistory(stateCancelHistory);

                //异步线程进行批量回滚处理所有子单取消订单
                meituanSplitMasterOrderCancelTask.executeSplitCancel(master_distributorOrderId_index,this);

                return  new Result<>(mtHotelOrderCancelApiResponseVo);
            }else{
                log.info("拆单主单forupdate异常："+master_distributorOrderId_index);
            }
        }
        return new Result("not",CommonConstants.REQUEST_ERROR);
    }


}
